﻿<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="stylesheet" type="text/css" href="../static/h-ui/css/H-ui.min.css" />
    <link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/H-ui.admin.css" />
    <link rel="stylesheet" type="text/css" href="../lib/Hui-iconfont/1.0.8/iconfont.css" />
    <link rel="stylesheet" type="text/css" href="../static/h-ui.admin/skin/default/skin.css" id="skin" />
    <link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/style.css" />
    <script type="text/javascript" src="../lib/My97DatePicker/4.8/WdatePicker.js"></script>
    <title>渠道表格报表</title>
    <style>
        .selectstyle {
            margin-right: 10px;
            height: 30px;
            border: 1px solid #5eb95e;
            border-radius: 4px;
            width: 120px;
            padding-left: 10px;
            text-align: left;
            background: #fff;
        }
    </style>
</head>

<body>

    <div class="page-container">
        <div class="searcharea">


            <input type="button" class="btnstyle" value="今日报告" onclick="readtodayreport();">

            <label>投诉渠道:
                <select name="sheetChannelId" class="selectstyle sheetChannelId">
                    <option value="0">所有渠道</option>
                </select>
            </label>

            <input type="text" value="" onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:00:00'})" id="datemax"
                class="input-text Wdate datestart" style="width:180px;">
            <span>-</span>
            <input type="text" value="" onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:00:00'})" id="datemax"
                class="input-text Wdate dateend" style="width:180px;">
            <input type="button" class="btnstyle" value="查询" onclick="readpagedata();">

            <input type="button" class="btnstyle" value="导出" onclick="_funcexecloutput();">

            <a class="ataprefresh" style="line-height:1.6em;margin-top:3px"
                href="javascript:location.replace(location.href);" title="刷新"><i class="Hui-iconfont">&#xe68f;</i></a>

        </div>
        <div class="mt-20">
            <table class="table table1 table-border table-bordered table-bg table-hover table-sort table-responsive">
                <thead>
                    <tr class="text-c">
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>

    <!--_footer 作为公共模版分离出去-->
    <script type="text/javascript" src="../lib/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="../lib/layer/2.4/layer.js"></script>
    <script type="text/javascript" src="../static/h-ui/js/H-ui.min.js"></script>
    <script type="text/javascript" src="../lib/jquery.contextmenu/jquery.contextmenu.r2.js"></script>
    <script type="text/javascript" src="../static/h-ui.admin/js/H-ui.admin.js"></script>
    <!--/_footer 作为公共模版分离出去-->
    <!--请在下方写此页面业务相关的脚本-->
    <!-- <script type="text/javascript" src="../lib/My97DatePicker/4.8/WdatePicker.js"></script> -->
    <script src="../lib/api.js"></script>

    <script>

        var channels = [];
        var complaints = [];

        $(window).ready(function () {

            _apiget("/api/sheet/complaintType?page=1&size=2000", false, function (code, obj) {
                if (code == 200) {
                    var datas = obj.items;
                    for (var k = 0; k < datas.length; k++) {
                        var item = datas[k];
                        complaints.push(item.complaintName);
                    }
                }
            });

            _apiget("/api/sheet/sheetChannel?page=1&size=2000", false, function (code, obj) {
                if (code == 200) {
                    var datas = obj.items;
                    var htmlStr = ""
                    for (var k = 0; k < datas.length; k++) {
                        var item = datas[k];
                        channels.push(item.channelName);
                        htmlStr += '<option value="' + item.id + '">' + item.channelName + '</option>';
                    }
                    $(".sheetChannelId").append(htmlStr);
                }
            });

            var daynow = new Date();
            daynow.setTime(daynow.getTime() - 3600000 * 24 * 31);
            $(".datestart").val(daynow.Format("yyyy-MM-dd 00:00:00"));

            var daylater = new Date();
            daylater.setTime(daylater.getTime() + 1000 * 3600);
            $(".dateend").val(daylater.Format("yyyy-MM-dd 00:00:00"));


            readpagedata();

        });

        function readpagedata() {


            var channelid = Number($(".sheetChannelId").val());

            var datestart = new Date($(".datestart").val());
            var dateend = new Date($(".dateend").val());

            if (datestart.getTime() >= dateend.getTime()) {

                layer.msg("开始时间和结束时时间不对，请重新输入！");
                return;
            }

            $(".table1").find("thead").find("tr").empty();
            $(".table1").find("tbody").empty();

            _apiget("/api/sheet/channelReport?begindate=" + $(".datestart").val() + "&enddate=" + $(".dateend").val() + "&channelid=" + channelid, true, function (code, obj) {
                if (code == 200) {
                    var datas = obj.items;
                    if (datas.length > 0) {
                        _showpagedata(datas);
                    } else {
                        layer.msg("当前条件没有查询到数据，请选择其他对象或者时间段再试！");
                    }
                    // pageobject.nums = obj.totalCount;
                    // var intid = parseInt(pageobject.nums / pageobject.counts); var less = parseInt(pageobject.nums % pageobject.counts); if (less > 0) { pageobject.pages = intid + 1; } else { pageobject.pages = intid; };
                }
            });

        }

        var pagedata = new Array();

        function _showpagedata(datas) {

            pagedata = new Array();

            for (var j = 0; j < channels.length; j++) {
                pagedata[channels[j]] = new Array();
            }



            for (var x = 0; x < datas.length; x++) {
                var item = datas[x];
                //某一个渠道
                if (pagedata.hasOwnProperty(item.sheetChannel.channelName)) {

                    var channeldata = pagedata[item.sheetChannel.channelName];

                    var day = item.dataDate.substr(0, 10);

                    //把渠道的这一天置空[]
                    if (!channeldata.hasOwnProperty(day)) {
                        channeldata[day] = new Array();
                    }

                    //写入默认数据？ 然后按照列替换？
                    for (var z = 0; z < complaints.length; z++) {
                        if (!channeldata[day].hasOwnProperty(complaints[z])) {
                            channeldata[day][complaints[z]] = 0;
                        }
                    }


                    if (item.dataContext != null && item.dataContext.length > 0) {
                        var das = JSON.parse(item.dataContext);
                        for (var j = 0; j < das.length; j++) {
                            var one = das[j];
                            if (channeldata[day].hasOwnProperty(one.ComplaintName)) {
                                channeldata[day][one.ComplaintName] = channeldata[day][one.ComplaintName] + one.Count;
                            }

                        }
                    }

                } else {
                    console.log("not found " + item.sheetChannel.channelName);
                }
                //渠道(sheet)--分类(column)-时间-数据(data)
            }

            // console.log(pagedata);

            // for(var ii in pagedata){
            //     console.log(ii);
            // }


            pagetempdata = pagedata;

            _functoTable(pagedata);
        }

        var pagetempdata = null;
        function _funcexecloutput() {

            // tableToExcel('.table1', 'abc');

            tableToExcel(pagetempdata);
        }

        //读取今日数据
        function readtodayreport() {

            $(".table1").find("thead").find("tr").empty();
            $(".table1").find("tbody").empty();

            _apiget("/api/sheet/Manage/ReadTodayChannelReport", true, function (code, datas) {
                if (code == 200) {
                    if (datas.length > 0) {
                        _showpagedata(datas);
                    } else {
                        layer.msg("没有今日的报告数据，应该是今日还没有创建工单，请稍后再试！");
                    }
                    // pageobject.nums = obj.totalCount;
                    // var intid = parseInt(pageobject.nums / pageobject.counts); var less = parseInt(pageobject.nums % pageobject.counts); if (less > 0) { pageobject.pages = intid + 1; } else { pageobject.pages = intid; };
                }
            });
        }

        //写入到UI表格中
        function _functoTable(pdata) {


            $(".table1").find("thead").find("tr").empty();
            $(".table1").find("tbody").empty();

            var thead = '<th>渠道</th><th>日期</th>';
            for (var k = 0; k < complaints.length; k++) {
                thead += '<th>' + complaints[k] + '</th>';
            }
            $(".table1").find(".text-c").append(thead);


            var datahtml = '';

            for (var sheet in pdata) {



                for (var day in pdata[sheet]) {

                    datahtml += '<tr>';
                    //写入时间列
                    datahtml += '<td>' + sheet + '</td><td>' + day + '</td>';
                    //写入数据列
                    for (var dat in pdata[sheet][day]) {
                        datahtml += '<td>' + pdata[sheet][day][dat] + '</td>';
                    }
                    datahtml += '</tr>';
                }



            }
            $(".table1").find("tbody").append(datahtml);


        }


        //base64转码
        var base64 = function (s) {
            return window.btoa(unescape(encodeURIComponent(s)));
        };
        //替换table数据和worksheet名字
        var format = function (s, c) {
            return s.replace(/{(\w+)}/g,
                function (m, p) {
                    return c[p];
                });
        }
        function tableToExcel(pdata) {
            var uri = 'data:application/vnd.ms-excel;base64,';
            // var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"' +
            //     'xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
            //     + '<x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets>'
            //     + '</x:ExcelWorkbook></xml><![endif]-->' +
            //     '</head><body ><table class="excelTable">{table}</table></body></html>';
            // if (!tableid.nodeType) tableid = document.getElementById(tableid);
            // var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
            // document.getElementById("excelOut").href = uri + base64(format(template, ctx));

            // var uri = 'data:application/vnd.ms-excel;base64,';
            // var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"' +
            //     'xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
            //     + '<x:Name>worksheet1</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet><x:ExcelWorksheet>'
            //     + '<x:Name>worksheet2</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets>'
            //     + '</x:ExcelWorkbook></xml><![endif]-->' +
            //     '</head><body ><table class="excelTable">{table}</table><table class="excelTable">{table}</table></body></html>';
            // // if (!tableid.nodeType) tableid = document.getElementById(tableid);
            // var ctx = {worksheet: sheetName || 'Worksheet', table: $(tableid).html()};
            // // document.getElementById("excelOut").href = uri + base64(format(template, ctx));
            // location.href=uri + base64(format(template, ctx));

            // > &gt;  < &lt;

            var xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                + '<?mso-application progid="Excel.Sheet"?>'
                + '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">';


            for (var sheet in pdata) {

                xml += '<Worksheet ss:Name="' + sheet + '"><Table ss:DefaultColumnWidth="150" ss:DefaultRowHeight="20">';

                //处理表首行
                xml += '<Row><Cell><Data ss:Type="String">日期</Data></Cell>'
                for (var k = 0; k < complaints.length; k++) {
                    xml += '<Cell><Data ss:Type="String">' + complaints[k] + '</Data></Cell>';
                }
                xml += '</Row>'


                for (var day in pdata[sheet]) {
                    xml += '<Row>';

                    //写入时间列
                    xml += '<Cell><Data ss:Type="String">' + day + '</Data></Cell>';

                    //写入数据列
                    for (var dat in pdata[sheet][day]) {
                        xml += '<Cell><Data ss:Type="Number">' + pdata[sheet][day][dat] + '</Data></Cell>';
                    }

                    xml += '</Row>';
                }


                xml += '</Table></Worksheet>';
            }

            xml += '</Workbook>';

            var downloadurl = uri + base64(xml);

            const a = document.createElement('a'); // 创建a标签
            a.setAttribute('download', downloadurl);// download属性
            a.setAttribute('filename', '日报告.xls');// download属性
            a.setAttribute('href', downloadurl);// href链接
            a.click();// 自执行点击事件

        }



    </script>


</body>

</html>